#include "mainwindow.h"

#include <QFile>
#include <QMessageBox>
#include <QApplication>
#include <QDebug>
#include <QDateTime>
#include <QMutex>
#include <QMessageLogContext>

void outputMessage(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    static QMutex mutex;
    mutex.lock();

    QString text;
    switch(type)
    {
    case QtDebugMsg:
        text = QString("D:");
        break;

    case QtWarningMsg:
        text = QString("W:");
        break;

    case QtCriticalMsg:
        text = QString("C:");
        break;

    case QtFatalMsg:
        text = QString("F:");
        break;
    case QtInfoMsg:
        text = QString("I:");
    }

    QString context_info = QString("File:(%1) Line:(%2)").arg(QString(context.file)).arg(context.line);
    //QString current_date_time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
    QString current_date_time = QDateTime::currentDateTime().toString("hh:mm:ss");
    QString current_date = QString("(%1)").arg(current_date_time);
    QString message = QString("%1 %2 %3 %4").arg(current_date).arg(text).arg(context_info).arg(msg);

    QString fileName = "logs/" + QDate::currentDate().toString("yyyyMMdd") + ".log";

    QFile file(fileName);
    file.open(QIODevice::WriteOnly | QIODevice::Append);
    QTextStream text_stream(&file);
    text_stream << message << "\r\n";
    file.flush();
    file.close();

    mutex.unlock();
}
int main(int argc, char *argv[])
{
    //注册MessageHandler
    qInstallMessageHandler(outputMessage);

    QApplication a(argc, argv);

    MainWindow w;
    w.show();
    return a.exec();
}
